<template>
  <el-dialog
    title="分配角色"
    :visible.sync="visible"
    :before-close="close"
    :append-to-body="true"
    width="400px"
  >
    <el-form :model="form" size="small">
      <el-form-item>
        <el-select v-model="selectRole" multiple placeholder="请选择">
          <el-option
            v-for="item in roleLists"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="close('reload')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getRoleLists, updateAdminRole } from "@/request/api";
export default {
  props: {
    visible: {
      default: false,
      type: Boolean,
    },
    form: {
      default: {},
      type: Object,
    },
  },
  data() {
    return {
      newForm: {},
      roleLists: [],
      selectRole: [],
    };
  },
  watch: {
    form(newVal, oldVal) {
      newVal.role && (this.selectRole = newVal.role.map((item) => item.id));
      this.newForm = JSON.parse(JSON.stringify(newVal));
    },
  },
  methods: {
    fetchRoleLists() {
      getRoleLists().then((res) => {
        if (res.code === 200) {
          this.roleLists = res.data;
        }
      });
    },
    close(reload) {
      if (reload == "reload") {
        this.$confirm("此操作将修改当前用户角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            updateAdminRole({
              adminId: this.newForm.id,
              roleIds: this.selectRole.join(","),
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.$emit("close", reload);
              }
            });
          })
          .catch(() => {});
      } else {
        this.$emit("close", reload);
      }
    },
  },
  created() {
    this.fetchRoleLists();
  },
};
</script>

<style lang="less" scoped>
</style>